package org.example.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// 通过 Executors工具类创建线程池
// 底层调用ThreadPoolExecutor方法创建    --三大方法（不安全）
public class ExecutorsDemo {

    public static void main(String[] args) {
        // ExecutorService threadPool = Executors.newSingleThreadExecutor();    // 单个线程
        ExecutorService threadPool = Executors.newFixedThreadPool(3);        // 指定线程数量
        // ExecutorService threadPool = Executors.newCachedThreadPool();           // 尽可能满足需求(不固定)

        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " ok");
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } finally {
            // 线程池用完，程序结束，关闭线程池
            threadPool.shutdown();
        }
    }
}
